package com.easyExcel.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

public class EasyExcelUtil {


    /**
     * 对外暴露的方法，导出 xls文件
     */
    public static <T>void exportXls(HttpServletResponse response,String fileName, String sheetName, Class<T> clazz,List<T> list) throws IOException {
        EasyExcelUtil.export(response, ExcelTypeEnum.XLS,fileName,sheetName,clazz,list);
    }
    public static <T>void exportXls(HttpServletResponse response,ExcelData<T> excelData) throws IOException {
        EasyExcelUtil.export(response,ExcelTypeEnum.XLS,excelData.getFileName(),excelData.getSheetName(),excelData.getClazz(),excelData.getDataList());
    }

    /**
     * 对外暴露的方法，导出 xlsx文件*/

    public static <T>void exportXlsx(HttpServletResponse response, String fileName, String sheetName, Class<T> clazz, List<T> list) throws IOException {
        EasyExcelUtil.export(response,ExcelTypeEnum.XLSX,fileName,sheetName,clazz,list);
    }
    public static <T>void exportXlsx(HttpServletResponse response,ExcelData<T> excelData) throws IOException {
        EasyExcelUtil.export(response,ExcelTypeEnum.XLSX,excelData.getFileName(),excelData.getSheetName(),excelData.getClazz(),excelData.getDataList());
    }



    /**
     * @param response  response
     * @param fileName  文件名
     * @param sheetName sheet名称
     * @param excelType    xls  xsx
     * @param clazz     实体类
     * @param list      数据
     * @throws IOException 抛出异常
     */
    private static <T>void export(HttpServletResponse response,ExcelTypeEnum excelType, String fileName, String sheetName,  Class<T> clazz, List<T> list) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setContentType("application/vnd.ms-excel");
        //字符集
        response.setCharacterEncoding("utf-8");
        //防止中文乱码
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + "." + excelType.getValue());
        //下载
        EasyExcel.write(response.getOutputStream(), clazz)
                .excelType(excelType)
                .sheet(sheetName)
                .doWrite(list);
    }
}
